/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.crypto.Mac;

public class HandleDataTableBannerDateV3 {
    
    public static final String KEYSPACE                             =   "AdsData";
    public static final String ColumFamly                           =   "BannerViewCountCf";
    public static final String ColumFamlyBannerClickCountCf         =   "BannerClickCountCf";
    public static final String ColumFamlyBannerViewCountCf          =   "BannerViewCountCf";

    public static final String ColumFamlyCampaignClickCountCf       =   "CampaignCountCf";
    public static final String ColumFamlyCampaignViewCountCf        =   "CampaignViewCountCf";
    
     public static final String ColumFamlyDateBanner_Geo_Counter    =   "DateBanner_Geo_Counter";
    
    public void handleData() throws ParseException, InterruptedException
    {
        CassandraAction cassAct = new CassandraAction(ACCOUNT.CLUSTERNAME ,ACCOUNT.URL, ACCOUNT.PORT);
        cassAct.initReadWirte(KEYSPACE);     
        List<Integer> listCampaigns = new ArrayList<>();       
        String currentDate = HandleDataTableDomainDate.handleDate();//2012-07-24
        //Debug.println("start time :" +TimeUtil.getCurrentTimeInStringForLog());
        //String currentDate = CONSTANT.Date;
        long first_time = System.currentTimeMillis();               
        MysqlDataManagerMain mysqldatamanager = new MysqlDataManagerMain();             
        //listCampaigns = mysqldatamanager.getCampaignIdBySliceCPM(currentDate);                
        //get all fraud click by date
        Map<String, Integer> fraudclicks = new HashMap<>();
        //fraudclicks = mysqlFaudClick.getAllFraudClickByBannerid(currentDate);
        //max value
        Map<Integer, Long> MaxValue = new HashMap<>();
        MaxValue = mysqldatamanager.getMaxValueDaybyBannerIdCPM(currentDate);
        //get all bannerid stop
        List allBannerStopAndPause = new ArrayList();        
        //allBannerStopAndPause = mysqldatamanager.getAllBanneridStoporPause(currentDate);        
        //tinh Geo     
        Map<String, String> geoMap = new HashMap<>();
        geoMap = HandleDataGeo.handleData();
        //lay du lieu tu bang domain
        Map<String, String> dataFromTableDomain = new HashMap<>();
        
        MysqlDataManager mysql86 = new MysqlDataManager();
        dataFromTableDomain = mysql86.getClickByDomainDateCPCandCPCplus(currentDate);
        
        StringBuilder sbff = new StringBuilder();
        Iterator iterator = dataFromTableDomain.entrySet().iterator();
        
        Map<Integer, String> uv_uc = new HashMap<>();
        uv_uc = mysqldatamanager.getUvUcByBannerid(currentDate);
        
	while (iterator.hasNext()) {
		Map.Entry mapEntry = (Map.Entry) iterator.next();
		//System.out.println("The key is: " + mapEntry.getKey()+ ",value is :" + mapEntry.getValue());			
                String key = (String) mapEntry.getKey();
                String value = (String) mapEntry.getValue();
                String camid        = key.split("_")[0];
                String bannerid     = key.split("_")[1];
                
                String totalclick   = value.split("_")[0];
                String totalview    = value.split("_")[1];
                String money        = value.split("_")[2];
                String geoValue     = geoMap.get(bannerid);

                String str = getDataCampaignAndBannerID(currentDate, camid, bannerid,Integer.valueOf(totalclick),Integer.valueOf(totalview),Integer.valueOf(money),fraudclicks,MaxValue,allBannerStopAndPause,uv_uc,geoValue);
                sbff.append(str);

            //xu li cho du lieu cuoi
            if(sbff.toString().length() > 10000)
            {
                MysqlDataManager mysql = new MysqlDataManager();
                String relStr = sbff.toString();
                String valInsert = relStr.substring(0, (relStr.length()-1));
                mysql.insertSliceDataCampaignAndBanner(valInsert);
                sbff.setLength(0);
            }
	}                        
        
        //xu li cho du lieu cuoi
        if(sbff.toString().length() > 1)
        {
            MysqlDataManager mysql = new MysqlDataManager();
            String relStr = sbff.toString();
            String valInsert = relStr.substring(0, (relStr.length()-1));
            mysql.insertSliceDataCampaignAndBanner(valInsert);
            sbff.setLength(0);
        }
        
        long last_time = System.currentTimeMillis();
        Debug.println("Thoi gian chay  :" +(last_time-first_time));
        Debug.println("success HandleDataTableBannerDate");

    }
    public static void removeDuplicateWithOrder(ArrayList arlList)
    {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = arlList.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
            newList.add(element);
        }
        arlList.clear();
        arlList.addAll(newList);
    }
    public static String getDataCampaignAndBannerID(String currentDay,String camId,String banId,int totalclick,int totalview,int money,Map<String, Integer> fraudclicks,Map<Integer, Long> MaxValue,List allBannerStopAndPause,Map uv_uc,String geoValue) throws ParseException
    {
            StringBuilder sb = new StringBuilder();
            int moneyCPM = Integer.valueOf(money);
            int clickCharge = 0 ;
            int fraud_click = 0 ;
            String uc ="";
            String uv ="";
            String mb = "";
            String mt = "";
            String mn = "";
            String other = "";
            if(uv_uc.containsKey(Integer.valueOf(banId)))
            {
                String uValue = (String) uv_uc.get(Integer.valueOf(banId));
                uc = uValue.split("_")[0];
                uv = uValue.split("_")[1];
            } else {
                uc = "0";
                uv = "0";
            }
                       
            mb = geoValue.split("_")[0];
            mt = geoValue.split("_")[1];
            mn = geoValue.split("_")[2];
            other = geoValue.split("_")[3];
            
            //if have fraudClick
            if(fraudclicks.containsKey(Integer.valueOf(banId)+"_"+currentDay))
            {                
                //if vuot qua 1.2 lan ngan sach thi tinh them 20%
                //clickcharge lay tu realclick - so click phan du so voi 120% ngan sach tu bang domaindate
                //so tien se la 120% ngan sach
                //int clickCharge = getClickChargeByBannerid(diffMoney, currentDay, Integer.valueOf(banId), ClickByDomainDate, PriceByDomain);                
                String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + totalclick +"," + totalview +"," + (totalclick-fraud_click) +","+ totalview + "," +(totalclick-fraud_click-clickCharge) +","+ totalview +","+ Integer.valueOf(uc) + "," + Integer.valueOf(uv) +",0,0,0,0,'" + currentDay + "'," + money +")";
                //String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +",0," + String.valueOf(countView) +",0,'" + currentDay + "',0)";
                sb.append(insertData).append(",");
            } else {
                String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + totalclick +"," + totalview +"," + (totalclick-fraud_click) +","+ totalview + "," +(totalclick-fraud_click) +","+ totalview+","+ Integer.valueOf(uc) + "," + Integer.valueOf(uv) +",0,0,0,0,'" + currentDay + "'," + money +")";
                //String insertData = "(" + Integer.valueOf(camId) + ", " + Integer.valueOf(banId) +"," + String.valueOf(countClick)+"," + (countClick-fraud_click) +",0," + String.valueOf(countView) +",0,'" + currentDay + "',0)";
                sb.append(insertData).append(",");
            } 
            //mysqldatamanager.insertDataCampaignAndBanner(String.valueOf(camId),String.valueOf(banId), String.valueOf(countClick), String.valueOf(countView), (prefixDB +i));
            return sb.toString();
    }

    
    public static int getClickChargeByBannerid(long totalMoney,String currentDay,int bannerid,Map<String, Long> ClickByDomainDate,Map<String, Integer> PriceByDomain)
    {
        Map<String, Long> DomainAndClick = new HashMap<>();
        int retValue    = 0;
        int totalClick  = 0;
        //lay cac domain tinh tien ra
        Set s = PriceByDomain.entrySet();        
        Iterator it=s.iterator();
        //tim so click ung voi moi domain va bannerid
        while(it.hasNext())
        {            
            Map.Entry m =(Map.Entry)it.next();
            //key là domain
            String key=(String)m.getKey();
            
            if(ClickByDomainDate.containsKey(String.valueOf(bannerid)+"_"+key+"_"+currentDay))
            {
                long numberClick = ClickByDomainDate.get(String.valueOf(bannerid)+"_"+key+"_"+currentDay);
                totalClick += numberClick;
                DomainAndClick.put(key, numberClick);
            }
        }
        //lay tung phan tu ra roi tinh clickcharge
        Set s1 = DomainAndClick.entrySet();
        Iterator it1=s1.iterator();
        while(it1.hasNext())
        {
            Map.Entry m =(Map.Entry)it1.next();
            //key là domain
            String  key=(String)m.getKey();
            //gia tri la tong click theo domain ung voi bannerid
            long    value     =   (Long)m.getValue();
            int     temp1     =   (int)(value/(totalClick));
            //lay gia moi domain
            int price = (int)PriceByDomain.get(key);
            //tinh tổng clickcharge
            retValue =+ (int) (temp1 * totalMoney/price);
        }
        return retValue;
    }
}
